<script setup lang="ts">
import SInfo from '@/components/common/info/SInfo.vue'
import { useInfo } from '@/composables/info-composable'
import type { ResultData } from '@/api/service'
import type { DashboardCardVo } from '@/type/Dashboard'
import { dashboardCardInfoApi, addDashboardCardApi, updateDashboardCardApi } from '@/api/dashboard-api'
import { ElMessage } from 'element-plus'

const props = defineProps<{
  query: { id?: string }
  close: () => void
}>()

const { statement, infoLoading, infoData, validErrors } = useInfo<DashboardCardVo>('CardInfo', getData)

function getData() {
  if (props.query.id !== undefined) {
    infoLoading.value = true
    dashboardCardInfoApi(props.query.id).then((response: ResultData<DashboardCardVo>) => {
      infoData.value = response.data
      infoLoading.value = false
    }).catch(() => {
      infoLoading.value = false
    })
  }
}

const methods = {
  save: () => {
    if (props.query.id !== undefined) {
      // 更新卡片
      updateDashboardCardApi(props.query.id, infoData.value).then(() => {
        ElMessage.success('更新成功')
        props.close()
      }).catch(() => {
        ElMessage.error('更新失败')
      })
    } else {
      // 新增卡片
      addDashboardCardApi(infoData.value).then(() => {
        ElMessage.success('新增成功')
        props.close()
      }).catch(() => {
        ElMessage.error('新增失败')
      })
    }
  },
  cancel: () => {
    props.close()
  }
}
</script>

<template>
  <s-info
    :data="infoData"
    :form-loading="infoLoading"
    :methods="methods"
    :statement="statement"
    :show-button="false"
  >
  </s-info>
</template>

<style scoped></style>